package minidb.index;


import static minidb.type.Const.*;
import minidb.buffer.Buffer;

public class indexHeader {
	private static final int slot = 50;
	public void Insert(String indexName, int pageNum){
		Buffer buf = bufpool.pin(2);
		int pos = buf.getInt(FREE);
		int newFree;
		int next = 0;
		while(pos+slot >= PAGE_SIZE){
			next = buf.getInt(NEXT_PAGE);
			if(next==0){
				next = dbFile.allocPage();
				int oldNext = buf.getInt(NEXT_PAGE);
				buf.putInt(NEXT_PAGE, next);
				bufpool.unpin(buf);
				buf = bufpool.pin(next);
				buf.putInt(NEXT_PAGE, oldNext);
				pos = INT_SIZE*4;
			}
			else{
				bufpool.unpin(buf);
				buf = bufpool.pin(next);
				pos = buf.getInt(FREE);
			}
		}
		newFree = pos+slot;
		buf.putString(pos, indexName);
		buf.putInt(pos+indexName.length()+1, pageNum);
		buf.putInt(FREE, newFree);
		bufpool.unpin(buf);
	}
	
	public int getIndex(String indexName){
		int pageNum;
		int next;
		Buffer buf = bufpool.pin(2);
		next = buf.getInt(NEXT_PAGE);
		int pos = INT_SIZE*4;
		int max = buf.getInt(INT_SIZE*3);
		while(true){
			while(pos+slot<=max){
				String s = buf.getString(pos);
				if(s.compareTo(indexName)==0){
					pageNum = buf.getInt(pos+s.length()+1);
					bufpool.unpin(buf);
					return pageNum;
				}
				pos+=slot;
			}
			next = buf.getInt(NEXT_PAGE);
			if(next==0)
				break;
			bufpool.unpin(buf);
			buf = bufpool.pin(next);
		}
		bufpool.unpin(buf);
		return 0;
	}
	
	public void deleteIndex(int pageNum){
		int next;
		Buffer buf = bufpool.pin(2);
		next = buf.getInt(NEXT_PAGE);
		int pos = INT_SIZE*4;
		while(true){
			while(pos+slot<PAGE_SIZE){
				String s = buf.getString(pos);
				if(buf.getInt(pos+s.length()+1)==pageNum){
					int free = buf.getInt(FREE);
					if(free-pos-slot!=0){
						java.nio.ByteBuffer bt = java.nio.ByteBuffer.allocate(PAGE_SIZE-pos-slot);
						buf.getByte(pos+slot, bt, PAGE_SIZE-pos-slot);
						buf.putByte(pos, bt, PAGE_SIZE-pos-slot);
					}
					buf.putInt(FREE, free-slot);
					bufpool.unpin(buf);
					return;
				}
				pos+=slot;
			}
			next = buf.getInt(NEXT_PAGE);
			if(next==0)
				break;
			bufpool.unpin(buf);
			buf = bufpool.pin(next);
		}
		bufpool.unpin(buf);
	}
}
